﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CLFramework.Web.Globalization;

[assembly: WebResource("ASB.MES.Web.UI.Scripts.common.js", "application/javascript")]

namespace CLFramework.Web.UI
{
    /// <summary>
    /// Web Page基类。
    /// </summary>
    public abstract class Page : System.Web.UI.Page
    {
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            //Initialize script files
            InitializeScript();
            base.OnPreRender(e);
        }

        #region OnPreInit

        /// <summary>
        /// Initializes Spring.NET page internals and raises the PreInit event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected override void OnPreInit(EventArgs e)
        {
            //if (Users.Current != null)
            //{
            //    User user = Users.Current;
            //    Theme = user.Theme;
            //    if (Master is IMainMasterPage)
            //    {
            //        MasterPageFile = string.Format("~/MasterPage/{0}/MainMasterPage.master", user.Theme);
            //    }
            //    else if (Master is ISubMasterPage)
            //    {
            //        MasterPageFile = string.Format("~/MasterPage/{0}/SubMasterPage.master", user.Theme);
            //    }
            //    //else if (Master is ISelectMasterPage)
            //    //{
            //    //    MasterPageFile = string.Format("~/MasterPage/{0}/SelectMasterPage.master", user.Theme);
            //    //}
            //}
            base.OnPreInit(e);
        }

        #endregion

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            //设置页面标题
            Header.Title = string.Concat(GetString("systemName"), " - Ver",
                                         GlobalSettings.SystemVersion);
            base.OnLoad(e);
        }

        #region InitializeScript

        /// <summary>
        /// 初始化脚本
        /// </summary>
        protected virtual void InitializeScript()
        {
            //注册系统变量
            //页面当前所处绝对路径
            string currentDirectory =
                string.Format("var systemCurrentDirectory='{0}';",
                              VirtualPathUtility.GetDirectory(Request.Url.AbsolutePath));
            //站点绝对根路径
            string absolutePath = string.Format(" var systemAbsolutePath='{0}';", Request.ApplicationPath.TrimEnd('/'));
            //应用程序窗口风格
            string windowStyle = string.Format("var systemWindowStyle='{0}';", WebApplicationSettings.WindowStyle);
            RegisterScript("systemVariables", currentDirectory + absolutePath + windowStyle);
            //注册系统脚本
            string systemScriptFile = Page.ClientScript.GetWebResourceUrl(typeof(Page),
                "ASB.MES.Web.UI.Scripts.common.js");
            RegisterScriptFile("systemScriptFile", systemScriptFile);
            string systemCurrentScriptFile = ResourceReader.GetThemesResourceUrl("core.js");
            if (File.Exists(Server.MapPath(systemCurrentScriptFile)))
            {
                RegisterScriptFile("systemCurrentScriptFile", systemCurrentScriptFile);
            }
        }

        #endregion

        #region ResourceReader

        private WebResourceReader resource;

        /// <summary>
        /// Gets the resource tool.
        /// </summary>
        /// <value>The resource tool.</value>
        public WebResourceReader ResourceReader
        {
            get
            {
                if (resource == null)
                {
                    resource = new WebResourceReader(Page);
                }
                return resource;
            }
        }

        #endregion

        #region GetString

        /// <summary>
        /// 根据资源名称取得资源，忽略大小写
        /// </summary>
        /// <param name="name">资源名称</param>
        /// <returns>资源值</returns>
        /// <remarks>搜索资源顺序为：当前系统资源->全局资源</remarks>
        public virtual string GetString(string name)
        {
            return ResourceReader.GetString(name);
        }

        /// <summary>
        /// 根据资源名称从指定系统资源取得资源，指定系统资源区分大小写，
        /// 资源名称忽略大小写
        /// </summary>
        /// <param name="resourceName">指定系统资源名称，形如：SYSTEM1.MODULE1</param>
        /// <param name="name">资源名称</param>
        /// <returns>资源值</returns>
        /// <remarks>搜索资源顺序为：指定系统资源->当前系统资源->全局资源</remarks>
        public virtual string GetString(string resourceName, string name)
        {
            return ResourceReader.GetString(resourceName, name);
        }

        #endregion

        #region GetObject

        /// <summary>
        /// 根据资源名称取得资源，忽略大小写
        /// </summary>
        /// <param name="name">资源名称</param>
        /// <returns>资源值</returns>
        /// <remarks>搜索资源顺序为：当前系统资源->全局资源</remarks>
        public virtual object GetObject(string name)
        {
            return ResourceReader.GetObject(name);
        }

        /// <summary>
        /// 根据资源名称从指定系统资源取得资源，指定系统资源区分大小写，
        /// 资源名称忽略大小写
        /// </summary>
        /// <param name="resourceName">指定系统资源名称，形如：SYSTEM1.MODULE1</param>
        /// <param name="name">资源名称</param>
        /// <returns>资源值</returns>
        /// <remarks>搜索资源顺序为：指定系统资源->当前系统资源->全局资源</remarks>
        public virtual object GetObject(string resourceName, string name)
        {
            return ResourceReader.GetObject(resourceName, name);
        }

        #endregion

        #region GetImage

        /// <summary>
        /// 取得指定图片资源的路径
        /// </summary>
        /// <param name="name">图片名称</param>
        /// <returns></returns>
        public virtual string GetImage(string name)
        {
            return ResourceReader.GetImage(name);
        }

        /// <summary>
        /// 取得指定图片资源的无语言路径
        /// </summary>
        /// <param name="path">图片在图片文件夹中的子文件夹</param>
        /// <param name="name">图片名称</param>
        /// <example>
        /// <code>GetImage("top", "topmenubg.gif");</code>
        /// </example>
        /// <returns></returns>
        public virtual string GetImage(string path, string name)
        {
            return ResourceReader.GetImage(path, name);
        }

        #endregion

        #region GetThemesResourceUrl

        /// <summary>
        /// Gets the themes resource URL.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <returns></returns>
        public virtual string GetThemesResourceUrl(string resourceName)
        {
            return ResourceReader.GetThemesResourceUrl(resourceName);
        }

        #endregion

        #region RegisterScriptFile

        /// <summary>
        /// 注册一个脚本文件到页面中。
        /// </summary>
        /// <param name="key">指定唯一的键值。</param>
        /// <param name="url">脚本文件的路径。</param>
        public void RegisterScriptFile(string key, string url)
        {
            if (!ClientScript.IsClientScriptIncludeRegistered(key))
            {
                ClientScript.RegisterClientScriptInclude(key, url);
            }
        }

        #endregion

        #region RegisterScript

        /// <summary>
        /// 注册一段脚本到页面中，无需指定script标记。
        /// </summary>
        /// <param name="key">指定唯一的键值。</param>
        /// <param name="script">脚本的内容。</param>
        public void RegisterScript(string key, string script)
        {
            if (!ClientScript.IsClientScriptBlockRegistered(key))
            {
                ClientScript.RegisterClientScriptBlock(GetType(), key, script, true);
            }
        }

        #endregion

        #region SelectTextBox

        /// <summary>
        /// Focus and highlight the text box
        /// </summary>
        /// <param name="textBox">The text box.</param>
        protected void SelectTextBox(TextBox textBox)
        {
            SelectControl(textBox.ClientID);
        }

        /// <summary>
        /// Focus and select the control
        /// </summary>
        /// <param name="control">The contrl.</param>
        protected void SelectControl(Control control)
        {
            SelectControl(control.ClientID);
        }

        /// <summary>
        /// Focus and select the control
        /// </summary>
        /// <param name="clientID">The client ID of control.</param>
        protected void SelectControl(string clientID)
        {
            const string scriptSelectControl = @"function {0}_focus(){{document.getElementById('{0}').select();}}
document.getElementById('{0}').attachEvent('onfocus', {0}_focus);
";

            string script = string.Format(scriptSelectControl, clientID);
            ClientScript.RegisterStartupScript(GetType(), string.Format("Control_{0}_FocusEvent", clientID),
                script, true);

            Page.SetFocus(clientID);

            script = string.Format("{0}_focus();", clientID);
            ClientScript.RegisterStartupScript(GetType(), string.Format("Control_{0}_Select", clientID), script, true);
        }

        #endregion

        #region CheckTimeOut

        /// <summary>
        /// 检查登陆是否超时。
        /// </summary>
        protected void CheckTimeOut()
        {
            //Session超时需要重新登陆
            //User user = Users.Current;
            //if ((user != null) && user.AlreadyLogin)
            //{
            //    user.LastOperateTime = DateTime.Now;
            //}
            //else
            //{
            //    string logoutUrl = "~/Logout.aspx?ReturnUrl=";
            //    logoutUrl += Server.UrlEncode(Request.Url.PathAndQuery);
            //    Response.Redirect(logoutUrl);
            //}
        }

        #endregion

        #region SetRequiredFieldValidatorText

        /// <summary>
        /// 设定指定的Validator的文本为默认必填文本。
        /// </summary>
        /// <param name="validator">The validator.</param>
        protected void SetRequiredFieldValidatorText(BaseValidator validator)
        {
            validator.Text = GetString("mustInput");
        }

        #endregion

        #region SetRequiredFieldValidatorsTextInPage

        /// <summary>
        /// 设定本页面里的所有RequiredFieldValidator的文本为默认文本。
        /// </summary>
        protected void SetRequiredFieldValidatorsTextInPage()
        {
            foreach (IValidator validator in Validators)
            {
                if (validator is RequiredFieldValidator)
                {
                    SetRequiredFieldValidatorText((RequiredFieldValidator)validator);
                }
            }
        }

        #endregion

        protected void ShowAlertMessage(string msg)
        {
            Utility.ScriptUtility.Alert(this, msg);
        }

        protected virtual Control FindControlRecursive(string id)
        {
            return FindControlRecursive(id, this);
        }
        protected virtual Control FindControlRecursive(string id, Control parent)
        {
            // If parent is the control we're looking for, return it  
            if (string.Compare(parent.ID, id, true) == 0)
                return parent;
            // Search through children  
            foreach (Control child in parent.Controls)
            {
                Control match = FindControlRecursive(id, child);
                if (match != null)
                    return match;
            }
            // If we reach here then no control with id was found  
            return null;
        }
    }
}
